﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using OfficeOpenXml;
using Entity;
using Controller;
namespace Web
{
    public class ExcelGenerator
    {
        public static string GenerateExcelForCustomerInvoiceById(int invoiceId)
        {
            CustInvoiceController custInvoiceController = new CustInvoiceController();
            CustomerInvoiceEntity customerInvoiceEntity = custInvoiceController.FindCustomerInvoiceById(invoiceId);
            DeliveryController deliveryController = new DeliveryController();
            IList<DeliveryEntity> deliveryEntities = deliveryController.FindDeliveryByInvoiceId(invoiceId);

            FileInfo template = new FileInfo(System.Web.HttpContext.Current.Server.MapPath("~")+"/excels/customer_invoice_template.xlsx");
            FileInfo invoice = new FileInfo(System.Web.HttpContext.Current.Server.MapPath("~") + "/excels/customer_invoice_"+customerInvoiceEntity.CustomerInvoiceNo+".xlsx");
            using(ExcelPackage excelPackage = new ExcelPackage(invoice,template))
            {
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets["CreditNote"];
                int lastRow = 43;
                int currentRow = 18;
                for (int i = 0; i < deliveryEntities.Count; i++)
                {
                    DeliveryEntity d = deliveryEntities[i];
                    if(i>4)
                    {
                        for (int j = 0; j < 5; j++)
                        {
                            worksheet.InsertRow(lastRow);
                            lastRow++;
                            for (int k = 1; k < 52; k++)
                            {
                                ExcelCell cell = worksheet.Cell(lastRow - 1, k);
                                worksheet.Cell(lastRow, k).StyleID = cell.StyleID;
                            }
                        }
                    }
                    worksheet.Cell(currentRow, 1).Value = (i+1).ToString();
                    worksheet.Cell(currentRow, 4).Value = d.ProductNo;
                    worksheet.Cell(currentRow + 1, 4).Value = "Invoice No:(" +d.InvoiceNo+")";
                    worksheet.Cell(currentRow + 2, 4).Value = "Yr PO No: (" + d.PoNo+")";
                    worksheet.Cell(currentRow + 3, 4).Value = d.Remark;

                    currentRow += 5;
                }

                excelPackage.Save();
            }
            return invoice.FullName.Substring(invoice.FullName.IndexOf("excels"));
        }
        public static string GenerateExcelForPackageListById(int invoiceId)
        {
            throw new NotImplementedException();
        }

        public static string GenerateExcelForVendorPOById(int vendorPOId)
        {
            throw new NotImplementedException();
        }
    }
}